import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wanke/block_page.dart';
import 'package:wanke/import_page.dart';
import 'add_page.dart';
import 'package:flutter/cupertino.dart';
import 'model/device_model.dart';
import 'model/group_model.dart';
import 'function.dart';
import 'dart:async';
import 'draw_record.dart';
import 'income_record.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'model/price_model.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'util/event.dart';
import 'download_page.dart';
import 'package:flutter_statusbar_manager/flutter_statusbar_manager.dart';

int decimal = 3;

class DevicePage extends StatefulWidget {
  @override
  _DevicePageState createState() => new _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {
  GlobalKey qrKey = new GlobalKey();
  RefreshController _refreshController = new RefreshController();
  String sortRule = "";
  String smsCode = "";
  String bindAddr = "";
  List<Map> drawErrors = [];
  bool drawing = false;
  Color mainColor = Colors.deepOrange;
  _DevicePageState() {
    setTheme();
    eventBus.on<Event>().listen((event) async {
      print(event.msg);
      switch (event.msg) {
        case "draw":
          drawAll();
          break;
        case "theme":
          setTheme();
          break;
        case "register":
          initGroups();
      }
    });
    //FlutterStatusbarManager.setStyle(StatusBarStyle.DARK_CONTENT);
    if (groups.length == 0) {
      initGroups();
    }
    if (price == "获取中") {
      initPrice();
    }
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      print("恢复");
    }
    if (state == AppLifecycleState.paused) {
      print("后台");
    }
  }

  setTheme() {
    themeColor.then((color) {
      mainColor = color;
      setState(() {});
    });
  }

  int findGroupIndex(DeviceModel find) {
    for (int i = 0; i < groups.length; i++) {
      for (DeviceModel device in groups[i].devices) {
        if (device == find) {
          return i;
        }
      }
    }
    return 0;
  }

  refreshAll(bool direction) async {
    initPrice();
    if (direction == false) {
      _refreshController.requestRefresh(true);
    } else {
      for (GroupModel group in groups) {
        await refreshGroup(group);
      }
      _refreshController.sendBack(true, RefreshStatus.completed);
    }
  }

  showBindImgCodeAlert(DeviceModel device, Map imgCode) {
    print(imgCode);

    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return new AlertDialog(
          title: new Text("绑定钱包"),
          content: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new Image.file(new File(imgCode['path'])),
              new TextField(
                onChanged: (verifyCode) {
                  this.smsCode = verifyCode;
                },
                style: new TextStyle(fontSize: 15.0, color: Colors.black),
                decoration: new InputDecoration(
                  hintText: "请输入图片验证码",
                ),
              ),
            ],
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text(
                "获取验证码",
              ),
              padding: EdgeInsets.all(0.0),
              onPressed: () async {
                var sendResult = await getSmsCode(device.account, sessionid: device.sessionid, userid: device.userid, imgCode: this.smsCode, codeKey1: imgCode['codeKey1'], codeKey2: imgCode['codeKey2']);
                this.smsCode = "";
                Navigator.of(context).pop();
                if (sendResult['iRet'] == 0) {
                  toast("验证码发送成功");
                  showBindSmsCodeAlert(device);
                } else if (sendResult['iRet'] == -121) {
                  toast("图片验证码错误");
                  var imgCode = await getImageCode(sendResult['sMsg']);
                  showBindImgCodeAlert(device, imgCode);
                } else if (sendResult['iRet'] == -122) {
                  toast("请输入图片验证码");
                  var imgCode = await getImageCode(sendResult['sMsg']);
                  showBindImgCodeAlert(device, imgCode);
                } else {
                  toast(sendResult['sMsg']);
                }
              },
            ),
            new FlatButton(
              onPressed: () async {
                Navigator.of(context).pop();
              },
              child: new Text(
                '关闭',
              ),
            ),
          ],
        );
      },
    );
  }

  showBindSmsCodeAlert(DeviceModel device) {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return new AlertDialog(
          title: new Text("绑定钱包"),
          content: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new TextField(
                onChanged: (inputAddr) {
                  this.bindAddr = inputAddr;
                },
                style: new TextStyle(fontSize: 15.0, color: Colors.black),
                decoration: new InputDecoration(
                  hintText: "请输入钱包地址",
                ),
              ),
              new TextField(
                onChanged: (verifyCode) {
                  this.smsCode = verifyCode;
                },
                style: new TextStyle(fontSize: 15.0, color: Colors.black),
                decoration: new InputDecoration(
                  hintText: "请输入验证码",
                ),
              ),
            ],
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text(
                "绑定",
              ),
              padding: EdgeInsets.all(0.0),
              onPressed: () async {
                var bindResult = await bindWallet(this.bindAddr, this.smsCode, device.sessionid, device.userid, device.device_id);
                this.smsCode = "";
                if (bindResult['iRet'] == 0) {
                  toast("钱包绑定成功");
                  refreshDevice(device);
                  Navigator.of(context).pop();
                } else {
                  toast(bindResult['sMsg']);
                }
              },
            ),
            new FlatButton(
              onPressed: () async {
                Navigator.of(context).pop();
              },
              child: new Text(
                '关闭',
              ),
            ),
          ],
        );
      },
    );
  }

  showUnbindImgCodeAlert(DeviceModel device, Map imgCode) {
    print(imgCode);

    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return new AlertDialog(
          title: new Text("绑定钱包"),
          content: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new Image.file(new File(imgCode['path'])),
              new TextField(
                onChanged: (verifyCode) {
                  this.smsCode = verifyCode;
                },
                style: new TextStyle(fontSize: 15.0, color: Colors.black),
                decoration: new InputDecoration(
                  hintText: "请输入图片验证码",
                ),
              ),
            ],
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text(
                "获取验证码",
              ),
              padding: EdgeInsets.all(0.0),
              onPressed: () async {
                var sendResult = await getSmsCode(device.account, sessionid: device.sessionid, userid: device.userid, imgCode: this.smsCode, codeKey1: imgCode['codeKey1'], codeKey2: imgCode['codeKey2']);
                this.smsCode = "";
                Navigator.of(context).pop();
                if (sendResult['iRet'] == 0) {
                  toast("验证码发送成功");
                  showUnbindSmsCodeAlert(device);
                } else if (sendResult['iRet'] == -121) {
                  toast("图片验证码错误");
                  var imgCode = await getImageCode(sendResult['sMsg']);
                  showUnbindImgCodeAlert(device, imgCode);
                } else if (sendResult['iRet'] == -122) {
                  toast("请输入图片验证码");
                  var imgCode = await getImageCode(sendResult['sMsg']);
                  showUnbindImgCodeAlert(device, imgCode);
                } else {
                  toast(sendResult['sMsg']);
                }
              },
            ),
            new FlatButton(
              onPressed: () async {
                Navigator.of(context).pop();
              },
              child: new Text(
                '关闭',
              ),
            ),
          ],
        );
      },
    );
  }

  showUnbindSmsCodeAlert(device) {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return new AlertDialog(
          title: new Text("解绑钱包"),
          content: new TextField(
            onChanged: (verifyCode) {
              this.smsCode = verifyCode;
            },
            style: new TextStyle(fontSize: 15.0, color: Colors.black),
            decoration: new InputDecoration(
              hintText: "请输入验证码",
            ),
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text(
                "解绑",
                style: new TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
              ),
              padding: EdgeInsets.all(0.0),
              onPressed: () async {
                var unbindResult = await unbindWallet(device.addr, this.smsCode, device.sessionid, device.userid);
                this.smsCode = "";
                if (unbindResult['iRet'] == 0) {
                  toast("钱包解绑成功");
                  refreshDevice(device);
                  Navigator.of(context).pop();
                } else {
                  toast(unbindResult['sMsg']);
                }
              },
            ),
            new FlatButton(
              onPressed: () async {
                Navigator.of(context).pop();
              },
              child: new Text(
                '关闭',
              ),
            ),
          ],
        );
      },
    );
  }

  drawAll() async {
    if (drawing) {
      toast("正在一键提币，请勿重复操作");
      return;
    } else {
      drawing = true;
    }
    drawErrors = [];
    int success = 0;
    int error = 0;
    for (GroupModel group in groups) {
      var res = await drawGroup(group, false);
      success += res['success'];
      error += res['error'];
    }
    drawing = false;
    if (drawErrors.length == 0) {
      showDialog<Null>(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text("提币结果"),
            content: new Text("共${success + error}台设备，成功$success台，失败$error台"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: new Text(
                  '确定',
                ),
              ),
            ],
          );
        },
      );
    } else {
      showModalBottomSheet(
        context: context,
        builder: (ctx) {
          return new SafeArea(
              child: new Container(
            child: new Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                new Container(
                  padding: EdgeInsets.all(5.0),
                  child: Text(
                    "提币结果：成功$success台，失败$error台",
                    style: new TextStyle(fontSize: 18.0),
                  ),
                ),
                new Expanded(
                  child: new ListView(
                    children: drawErrors.map(
                      (err) {
                        return new ListTile(
                          title: new Text(err['device'].device_name),
                          subtitle: new Text(err['reason']),
                          trailing: new IconButton(
                            tooltip: "重试",
                            icon: new Icon(
                              Icons.replay,
                            ),
                            onPressed: () {
                              drawDevice(err['device'], true);
                            },
                          ),
                        );
                      },
                    ).toList(),
                  ),
                ),
              ],
            ),
          ));
        },
      );
    }
  }

  Future<Map> drawGroup(GroupModel group, bool single) async {
    if (single) {
      drawErrors = [];
      if (drawing) {
        toast("正在一键提币，请勿重复操作");
        return null;
      } else {
        drawing = true;
      }
    }
    Map result = {"success": 0, "error": 0};
    for (DeviceModel device in group.devices) {
      bool res = await drawDevice(device, false);
      if (res) {
        result['success']++;
      } else {
        result['error']++;
      }
    }
    if (single) {
      drawing = false;
      if (drawErrors.length == 0) {
        showDialog<Null>(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提币结果"),
              content: new Text("共${result['success'] + result['error']}台设备，成功${result['success']}台，失败${result['error']}台"),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '确定',
                  ),
                ),
              ],
            );
          },
        );
      } else {
        showModalBottomSheet(
          context: context,
          builder: (ctx) {
            return new Container(
              child: new Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new Container(
                    padding: EdgeInsets.all(5.0),
                    child: Text(
                      "提币结果：成功${result['success']}台，失败${result['error']}台",
                      style: new TextStyle(fontSize: 18.0),
                    ),
                  ),
                  new Expanded(
                    child: new ListView(
                      children: drawErrors.map(
                        (err) {
                          return new ListTile(
                            title: new Text(err['device'].device_name),
                            subtitle: new Text(err['reason']),
                            trailing: new IconButton(
                              tooltip: "重试",
                              icon: new Icon(
                                Icons.replay,
                              ),
                              onPressed: () {
                                drawDevice(err['device'], true);
                              },
                            ),
                          );
                        },
                      ).toList(),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      }
    }
    return result;
  }

  Future<bool> drawDevice(DeviceModel device, bool single) async {
    if (single) {
      if (drawing) {
        toast("正在一键提币，请勿重复操作");
        return false;
      }
    }
    var isLogin = false;
    bool loginStatus = true;
    if (!isLogin) {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      var drawResult = await applyToDraw(device.sessionid, device.userid);
      if (drawResult['iRet'] == 0) {
        if (single == true) {
          toast("申请提币成功");
        }
        return true;
      } else {
        drawErrors.add({"device": device, "reason": drawResult['sMsg']});
        if (single == true) {
          showDialog<Null>(
            context: context,
            builder: (context) {
              return new AlertDialog(
                title: new Text("提币失败"),
                content: new Text(drawResult['sMsg']),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: new Text(
                      '确定',
                    ),
                  ),
                ],
              );
            },
          );
        }
        return false;
      }
    } else {
      drawErrors.add({"device": device, "reason": "申请提币失败，请重试"});
      if (single == true) {
        showDialog<Null>(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提币失败"),
              content: new Text("申请提币失败，请重试"),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () async {
                    Navigator.of(context).pop();
                  },
                  child: new Text(
                    '取消',
                  ),
                ),
              ],
            );
          },
        );
      }
      return false;
    }
  }

  initPrice() async {
    var data = await getPlayWkcPrice();
    if (data != null) {
      price = data['current'];
      if (mounted) {
        setState(() {});
      }
    } else {
      price = "err";
    }
  }

  Widget indexHeader() {
    return new Container(
      color: mainColor,
      child: new Column(
        children: <Widget>[
          new Container(
            padding: EdgeInsets.only(top: 0.0, bottom: 10.0),
            child: new Row(
              children: <Widget>[
                new Column(
                  children: <Widget>[],
                ),
                new Expanded(
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        "昨日收入",
                        style: new TextStyle(color: Colors.white30, fontSize: 12.0),
                      ),
                      new Text(
                        yesterdayIncome.toStringAsFixed(decimal),
                        style: new TextStyle(color: Colors.white, fontSize: 24.0),
                      ),
                      new Text(
                        "参考价:$price",
                        style: new TextStyle(color: Colors.white, fontSize: 12.0),
                      ),
                    ],
                  ),
                ),
                new Column(
                  children: <Widget>[],
                ),
              ],
            ),
          ),
          new Container(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                new Column(
                  children: <Widget>[
                    new Text(
                      "昨日平均",
                      style: new TextStyle(
                        color: Colors.white70,
                        fontSize: 12.0,
                      ),
                    ),
                    new Text(
                      (yesterdayIncome / (deviceCount > 0 ? deviceCount : 1)).toStringAsFixed(decimal),
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
                new Column(
                  children: <Widget>[
                    new Text(
                      "前日收入",
                      style: new TextStyle(
                        color: Colors.white70,
                        fontSize: 12.0,
                      ),
                    ),
                    new Text(
                      prevdayIncome.toStringAsFixed(decimal),
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
                new Column(
                  children: <Widget>[
                    new Text(
                      "累计收入",
                      style: new TextStyle(
                        color: Colors.white70,
                        fontSize: 12.0,
                      ),
                    ),
                    new Text(
                      totalIncome.toStringAsFixed(decimal),
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
                new Column(
                  children: <Widget>[
                    new Text(
                      "可提链克",
                      style: new TextStyle(
                        color: Colors.white70,
                        fontSize: 12.0,
                      ),
                    ),
                    new Text(
                      balanceIncome.toStringAsFixed(decimal),
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ],
            ),
            color: new Color.fromRGBO(0, 0, 0, 0.1),
            padding: EdgeInsets.only(
              top: 5.0,
              bottom: 5.0,
            ),
          ),
        ],
      ),
    );
  }

  bool isPrivate = true;
  hideInfo(String info) {
    if (isPrivate) {
      return "test";
    } else {
      return info;
    }
  }

  List<String> groupsArray() {
    List<String> groupsArr = new List();
    groups.forEach((group) {
      groupsArr.add(group.name);
    });
    return groupsArr;
  }

  deleteDevice(DeviceModel device) {
    showDialog<Null>(
      context: context,
      builder: (context) {
        return new AlertDialog(
          title: new Text("删除设备"),
          content: new Text("确定要删除此设备吗"),
          actions: <Widget>[
            new FlatButton(
              onPressed: () {
                device.delete().then((res) {
                  if (res) {
                    toast("设备已删除");
                    groups[findGroupIndex(device)].devices.remove(device);
                    if (mounted) {
                      setState(() {});
                    }
                    Navigator.pop(context);
                  } else {
                    toast("删除失败，请重试");
                  }
                });
              },
              child: new Text(
                '删除',
                style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
              ),
            ),
            new FlatButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: new Text(
                '取消',
              ),
            ),
          ],
        );
      },
    );
  }

  Future<bool> refreshGroup(GroupModel group) async {
    for (DeviceModel device in group.devices) {
      await refreshDevice(device);
    }
    return true;
  }

  Future<bool> refreshDevice(DeviceModel device) async {
    setState(() {
      device.loading = true;
    });
    bool loginStatus = true;
    bool isLogin = await checkLogin(device.sessionid, device.userid);
    if (isLogin) {
      print("登录有效");
    } else {
      print("登录无效");
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.deviceid, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("开始获取账号信息");
      var accountInfo = await getAccountInfo(sessionid: device.sessionid, userid: device.userid);
      if (accountInfo != null) {
        print("账号信息获取成功");
        device.addr = accountInfo['addr'];
        //balanceIncome = balanceIncome - device.balance_income + double.parse(accountInfo['balance']);
        device.balance_income = double.parse(accountInfo['balance']);
      } else {
        print("账号信息获取失败");
      }

      print("开始获取设备信息");
      var deviceInfo = await getDeviceInfo(device.sessionid, device.userid);
      if (deviceInfo == null) {
        print("获取设备信息失败");
        device.ip_addr = "获取失败";
        device.province = "获取";
        device.isp = "失败";
      } else if (deviceInfo.length == 0) {
        device.is_bind = false;
        print("未绑定设备");
        device.update();
        device.loading = false;
        if (mounted) {
          setState(() {});
        }
        return false;
      } else {
        print("获取设备信息成功");
        device.is_bind = true;
        device.status = deviceInfo[0]['status'];
        device.exception_message = deviceInfo[0]['exception_message'];
        device.bind_time = convertTime(deviceInfo[0]['bind_time']);
        device.province = deviceInfo[0]['ip_info']['province'];
        device.city = deviceInfo[0]['ip_info']['city'];
        device.isp = deviceInfo[0]['ip_info']['isp'];
        print(device.isp);
        device.lan_ip = deviceInfo[0]['lan_ip'];
        device.device_name = deviceInfo[0]['device_name'];
        device.device_id = deviceInfo[0]['device_id'];
        device.device_sn = deviceInfo[0]['device_sn'];
        device.peerid = deviceInfo[0]['peerid'];
        device.ip_addr = deviceInfo[0]['ip'];
        print(device.ip_addr);
        device.hardware_model = deviceInfo[0]['hardware_model'];
        device.mac_address = deviceInfo[0]['mac_address'];
        device.system_version = deviceInfo[0]['system_version'];
        device.iswanke = deviceInfo[0]['features']['onecloud_coin'] == false ? "0" : "1";
        device.bind_days = deviceInfo[0]['features']['onecloud_coin'] == false ? "" : getTimeLong(deviceInfo[0]['features']['onecloud_coin']);
      }
      print("开始获取收入信息");
      if (device.income_day == getDate(-1)) {
        print("无需获取收入信息");
      } else {
        var curDay = new DateTime.now().day;
        var incomeInfo = await getIncomeRecord(sessionid: device.sessionid, userid: device.userid);
        if (incomeInfo == null) {
          print("获取收入信息失败");
        } else {
          print("获取收入信息成功");
          List incomeArr = incomeInfo['incomeArr'];
          if (curDay <= 2) {
            var preMonthInfo = await getIncomeRecord(sessionid: device.sessionid, userid: device.userid, month: new DateTime.now().month);
            incomeArr.addAll(preMonthInfo['incomeArr']);
          }
          if (incomeArr.length > 1) {
//          group.yesterdayIncome = group.yesterdayIncome - device.yesterday_income + double.parse(incomeArr[0]['num']);
//          group.prevdayIncome = group.prevdayIncome - device.prevday_income + double.parse(incomeArr[1]['num']);
            //yesterdayIncome = yesterdayIncome - device.yesterday_income + double.parse(incomeArr[0]['num']);
            //prevdayIncome = prevdayIncome - device.prevday_income + double.parse(incomeArr[1]['num']);
            //totalIncome = totalIncome - device.total_income + incomeInfo['totalIncome'];
            device.income_day = incomeArr[0]['date'];
            device.total_income = incomeInfo['totalIncome'];
            device.yesterday_income = double.parse(incomeArr[0]['num']);
            device.prevday_income = double.parse(incomeArr[1]['num']);
          } else if (incomeArr.length > 0) {
//          group.prevdayIncome = group.prevdayIncome - device.prevday_income + double.parse(incomeArr[1]['num']);
            //yesterdayIncome = yesterdayIncome - device.yesterday_income + double.parse(incomeArr[0]['num']);
            device.yesterday_income = double.parse(incomeArr[0]['num']);
            device.income_day = incomeArr[0]['date'];
            device.total_income = incomeInfo['totalIncome'];
            device.yesterday_income = double.parse(incomeArr[0]['num']);
          }
        }
      }
      if (device.status != "offline") {
        print("开始获取磁盘信息");
        var usbInfo = await getUsbInfo(device.sessionid, device.userid, device.device_id);
        print(usbInfo);
        if (usbInfo == null) {
          print("获取磁盘信息失败");
        } else {
          device.capacity_1 = usbInfo['capacity_1'];
          device.used_1 = usbInfo['used_1'];
          device.capacity_2 = usbInfo['capacity_2'];
          device.used_2 = usbInfo['used_2'];
        }
        device.update();
        device.loading = false;
        if (mounted) {
          setState(() {});
        }
      } else {
        print("设备不在线，无需获取磁盘信息");

        if (mounted) {}
      }

      return true;
    } else {
      device.loading = false;
      print("登录出错XX");
      return false;
    }
  }

  initGroups() async {
    groups = [];
    var existGroups = await getGroups();
    deviceCount = await getDeviceCount();
    if (existGroups != null) {
      for (var i = 0; i < existGroups.length; i++) {
        var groupDevices = await getDevicesByGroup(existGroups[i]['id']);
        if (groupDevices != null) {
          List<DeviceModel> addDevices = [];
          groupDevices.forEach((device) {
            addDevices.add(new DeviceModel().fromMap(device));
          });
          groups.add(
            new GroupModel(id: existGroups[i]['id'], name: existGroups[i]['name'], devices: addDevices),
          );
        } else {
          groups.add(
            new GroupModel(id: existGroups[i]['id'], name: existGroups[i]['name'], devices: []),
          );
        }
      }
    } else {
      addGroup("默认分组");
      groups.add(
        new GroupModel(id: 1, name: "默认分组", devices: []),
      );
    }
    if (mounted) {
      setState(() {});
    }
    refreshAll(false);
  }

  Widget _buildGroup(GroupModel group) {
    FlutterStatusbarManager.setStyle(StatusBarStyle.LIGHT_CONTENT);
    return new Container(
      child: new Column(
        children: <Widget>[
          new Container(
            decoration: new BoxDecoration(
              color: new Color(0xFFEEEEEE),
              border: new Border(
                bottom: new BorderSide(color: Colors.black12, width: 0.5),
              ),
            ),
            padding: EdgeInsets.all(5.0),
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      new Padding(
                        padding: EdgeInsets.only(right: 3.0),
                        child: new Text(
                          group.name,
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: EdgeInsets.only(right: 3.0),
                        child: new Text(
                          group.devices.length.toString() + "台",
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: EdgeInsets.only(right: 3.0),
                        child: new Text(
                          "昨:" + group.yesterdayIncome.toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: EdgeInsets.only(right: 3.0),
                        child: new Text(
                          "均:" + (group.yesterdayIncome / (group.devices.length > 0 ? group.devices.length : 1)).toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Text(
                        "前:" + group.prevdayIncome.toStringAsFixed(decimal),
                        style: new TextStyle(
                          color: Colors.black,
                          fontSize: 12.0,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ],
                  ),
                ),
                new Padding(
                  padding: EdgeInsets.only(left: 1.5, right: 1.5),
                  child: new CupertinoButton(
                    pressedOpacity: 0.8,
                    child: new Icon(Icons.settings, size: 16.0, color: Colors.black54),
                    onPressed: () {
                      showModalBottomSheet(
                          context: context,
                          builder: (ctx) {
                            return new Container(
                              child: new Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  new ListTile(
                                    onTap: () {
                                      String newGroupName = group.name;
                                      Navigator.of(context).pop();
                                      showDialog<Null>(
                                        context: context,
                                        builder: (context) {
                                          return new AlertDialog(
                                            title: new Text("修改组名"),
                                            content: new TextField(
                                              controller: new TextEditingController(text: group.name),
                                              decoration: new InputDecoration(
                                                hintText: '请输入分组名',
                                                labelText: "分组名",
                                              ),
                                              onChanged: (value) {
                                                newGroupName = value;
                                              },
                                            ),
                                            actions: <Widget>[
                                              new FlatButton(
                                                onPressed: () async {
                                                  if (newGroupName == "") {
                                                    toast("分组名不能为空");
                                                    return;
                                                  }
                                                  group.name = newGroupName;
                                                  setState(() {});
                                                  var updateResult = await group.update();
                                                  if (updateResult) {
                                                    toast("组名修改成功");
                                                    Navigator.of(context).pop();
                                                  } else {
                                                    toast("组名修改失败，请重试");
                                                  }
                                                },
                                                child: new Text(
                                                  '修改',
                                                ),
                                              ),
                                              new FlatButton(
                                                onPressed: () async {
                                                  Navigator.of(context).pop();
                                                },
                                                child: new Text(
                                                  '取消',
                                                ),
                                              ),
                                            ],
                                          );
                                        },
                                      );
                                    },
                                    leading: new Icon(Icons.edit),
                                    title: new Text("修改组名"),
                                  ),
                                  new Divider(
                                    height: 1.0,
                                  ),
                                  new ListTile(
                                    onTap: () {
                                      Navigator.of(context).pop();
                                      drawGroup(group, true);
                                    },
                                    leading: new ImageIcon(AssetImage("images/withdraw.png")),
                                    title: new Text("快捷提币"),
                                  ),
                                  new Divider(
                                    height: 1.0,
                                  ),
//                                  new ListTile(
//                                    onTap: () {
//
//                                    },
//                                    leading: new ImageIcon(AssetImage("images/unlink.png")),
//                                    title: new Text("快捷解绑"),
//                                  ),
//                                  new Divider(
//                                    height: 1.0,
//                                  ),
                                  new ListTile(
                                    onTap: () {
                                      Navigator.of(context).pop();
                                      if (group.id == 1) {
                                        toast("默认分组无法删除");
                                        return;
                                      }
                                      if (groups.length == 1) {
                                        toast("请至少保留一个分组");
                                        return;
                                      }
                                      print(group.devices.length);
                                      showDialog<Null>(
                                        context: context,
                                        builder: (context) {
                                          return new AlertDialog(
                                            title: new Text("删除分组"),
                                            content: new Text(group.devices.length > 0 ? "当前分组内存在设备，请选择操作" : "确定删除此分组？"),
                                            actions: <Widget>[
                                              group.devices.length > 0
                                                  ? new Column(
                                                      crossAxisAlignment: CrossAxisAlignment.end,
                                                      mainAxisSize: MainAxisSize.min,
                                                      children: <Widget>[
                                                        new FlatButton(
                                                          onPressed: () async {
                                                            Navigator.of(context).pop();
                                                            var deleteDeviceResult = await deleteDeviceByGroupId(group.id);
                                                            if (deleteDeviceResult) {
                                                              group.devices = [];
                                                            } else {
                                                              toast("删除设备失败");
                                                              return;
                                                            }
                                                            var deleteGroupResult = await deleteGroup(group.id);
                                                            if (deleteGroupResult) {
                                                              groups.remove(group);
                                                              toast("设备和分组删除成功");
                                                            } else {
                                                              toast("设备删除成功，删除分组失败");
                                                            }
                                                          },
                                                          child: new Text(
                                                            '同时删除设备',
                                                          ),
                                                        ),
                                                        new FlatButton(
                                                          onPressed: () async {
                                                            Navigator.of(context).pop();
                                                            var updateResult = await updateGroupId(group.id, groups.indexOf(group) == 0 ? groups[1].id : groups[0].id);
                                                            if (updateResult != null && updateResult) {
                                                              groups.indexOf(group) == 0 ? groups[1].devices.addAll(group.devices) : groups[0].devices.addAll(group.devices);
                                                              group.devices = [];
                                                            } else {
                                                              toast("移动设备失败，请重试");
                                                              return;
                                                            }
                                                            var deleteGroupResult = await deleteGroup(group.id);
                                                            if (deleteGroupResult) {
                                                              groups.remove(group);
                                                              toast("移动设备并删除分组成功");
                                                            } else {
                                                              toast("移动设备成功，删除分组失败");
                                                            }
                                                            setState(() {});
                                                          },
                                                          child: new Text(
                                                            '将设备移至' + (groups.indexOf(group) == 0 ? groups[1].name : groups[0].name),
                                                          ),
                                                        ),
                                                        new FlatButton(
                                                          onPressed: () {
                                                            Navigator.of(context).pop();
                                                          },
                                                          child: new Text(
                                                            '取消',
                                                          ),
                                                        ),
                                                      ],
                                                    )
                                                  : new Row(
                                                      children: <Widget>[
                                                        new FlatButton(
                                                            onPressed: () async {
                                                              var deleteGroupResult = await deleteGroup(group.id);
                                                              if (deleteGroupResult) {
                                                                groups.remove(group);
                                                                toast("删除分组成功");
                                                              } else {
                                                                toast("删除分组失败");
                                                              }
                                                              Navigator.of(context).pop();
                                                              setState(() {});
                                                            },
                                                            child: new Text("删除分组")),
                                                        new FlatButton(
                                                            onPressed: () {
                                                              Navigator.of(context).pop();
                                                            },
                                                            child: new Text("取消")),
                                                      ],
                                                    ),
                                            ],
                                          );
                                        },
                                      );
                                    },
                                    leading: new ImageIcon(
                                      AssetImage("images/delete.png"),
                                      color: Colors.red,
                                    ),
                                    title: new Text(
                                      "删除分组",
                                      style: new TextStyle(color: Colors.red),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          });
                    },
                    padding: EdgeInsets.all(0.0),
                    minSize: 22.0,
                  ),
                ),
                new Padding(
                  padding: EdgeInsets.only(left: 1.5, right: 1.5),
                  child: new CupertinoButton(
                    pressedOpacity: 0.8,
                    child: new Icon(Icons.refresh, size: 18.0, color: Colors.black54),
                    onPressed: () {
                      refreshGroup(group);
                    },
                    padding: EdgeInsets.all(0.0),
                    minSize: 22.0,
                  ),
                ),
                new Padding(
                  padding: EdgeInsets.only(left: 1.5, right: 1.5),
                  child: new CupertinoButton(
                    pressedOpacity: 1.0,
                    child: new Icon(group.showDevice ? Icons.expand_more : Icons.expand_less, size: 22.0, color: Colors.black54),
                    onPressed: () {
                      group.showDevice = !group.showDevice;
                      if (mounted) {
                        setState(() {});
                      }
                    },
                    padding: EdgeInsets.all(0.0),
                    minSize: 22.0,
                  ),
                ),
              ],
            ),
          ),
          group.showDevice
              ? new Column(
                  children: group.devices.map(_buildDevice).toList(),
                )
              : new Column(),
        ],
      ),
    );
  }

  Widget _buildDevice(DeviceModel device) {
    return new Container(
      decoration: new BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.black38, width: 0.5),
        ),
      ),
      child: device.is_bind == false
          ? FlatButton(
              color: Colors.white,
              padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 5.0, right: 1.0),
              onPressed: () async {
                var deviceStr = await scan();
                if (deviceStr == null) {
                  return;
                }
                var device_id = deviceStr.replaceAll("http://account.onethingpcs.com/b?d=", "");
                print(device_id);
                var bindResult = await bindDevice(device.sessionid, device.userid, device_id);
                if (bindResult) {
                  refreshDevice(device);
                }
              },
              child: new Row(
                children: <Widget>[
                  new CupertinoButton(
                    minSize: 22.0,
                    child: new Image.asset(
                      "images/delete.png",
                      width: 22.0,
                    ),
                    onPressed: () async {
                      deleteDevice(device);
                    },
                    padding: EdgeInsets.only(right: 5.0),
                  ),
                  new Expanded(
                    child: new Column(
                      children: <Widget>[
                        new Text(
                          device.account,
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                        new SizedBox(
                          height: 5.0,
                        ),
                        new Text(
                          "点击绑定设备",
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new AnimatedCrossFade(
                    duration: const Duration(milliseconds: 200),
                    firstChild: new CupertinoActivityIndicator(
                      radius: 10.0,
                    ),
                    secondChild: new CupertinoButton(
                        minSize: 20.0,
                        padding: EdgeInsets.all(0.0),
                        child: new Icon(Icons.refresh, size: 20.0, color: Colors.black54),
                        onPressed: () {
                          refreshDevice(device);
                        }),
                    crossFadeState: device.loading ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                  ),
                ],
              ),
            )
          : new FlatButton(
              padding: EdgeInsets.only(
                top: 10.0,
              ),
              child: new Column(
                children: <Widget>[
                  new Row(
                    children: <Widget>[
                      new Expanded(
                        flex: 2,
                        child: new Column(
                          children: <Widget>[
                            new Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                new Icon(
                                  Icons.brightness_1,
                                  color: device.status == "online" ? Colors.green : device.status == "exception" ? Colors.red : Colors.grey,
                                  size: 12.0,
                                ),
                                new Text(
                                  device.device_name == "" ? "获取中" : device.device_name,
                                  overflow: TextOverflow.clip,
                                  softWrap: false,
                                  style: new TextStyle(
                                    color: Colors.black,
                                    fontSize: 12.0,
                                    fontWeight: FontWeight.normal,
                                  ),
                                )
                              ],
                            ),
                            new SizedBox(
                              height: 5.0,
                            ),
                            new Text(
                              device.status == "offline" ? "设备离线" : device.capacity_1 == 0 && device.capacity_2 == 0 ? "无磁盘" : "${convertSize((device.used_1 ?? 0) + (device.used_2 ?? 0))}/${convertSize((device.capacity_1 ?? 0) + device.capacity_2 ?? 0)}",
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                              overflow: TextOverflow.clip,
                              softWrap: false,
                            ),
                          ],
                        ),
                      ),
                      new Expanded(
                        flex: 2,
                        child: new Column(
                          children: <Widget>[
                            new Text(
                              "昨:" + device.yesterday_income.toStringAsFixed(decimal),
                              style: new TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.normal,
                                fontSize: 12.0,
                              ),
                            ),
                            new SizedBox(
                              height: 5.0,
                            ),
                            new Text(
                              "前:" + device.prevday_income.toStringAsFixed(decimal),
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                          ],
                        ),
                      ),
                      new Expanded(
                        flex: 2,
                        child: new Column(
                          children: <Widget>[
                            new Text(
                              "余:" + device.balance_income.toStringAsFixed(decimal),
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                              textAlign: TextAlign.left,
                            ),
                            new SizedBox(
                              height: 5.0,
                            ),
                            new Text(
                              "总:" + device.total_income.toStringAsFixed(decimal),
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                          ],
                        ),
                      ),
                      new Expanded(
                        flex: 3,
                        child: new Column(
                          children: <Widget>[
                            new Text(
                              device.ip_addr == null ? "获取中" : device.ip_addr,
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                            new SizedBox(
                              height: 5.0,
                            ),
                            new Text(
                              (device.city == null ? device.province : device.city) + "-" + device.isp,
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                          ],
                        ),
                      ),
                      new AnimatedCrossFade(
                        duration: const Duration(milliseconds: 200),
                        firstChild: new CupertinoActivityIndicator(
                          radius: 10.0,
                        ),
                        secondChild: new CupertinoButton(
                            minSize: 20.0,
                            padding: EdgeInsets.all(0.0),
                            child: new Icon(Icons.refresh, size: 20.0, color: Colors.black54),
                            onPressed: () {
                              refreshDevice(device);
                            }),
                        crossFadeState: device.loading ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                      ),
                    ],
                  ),
                  device.exception_message == null || device.exception_message == ""
                      ? new Container(
                          padding: new EdgeInsets.only(bottom: 10.0),
                        )
                      : new Row(
                          children: <Widget>[
                            new Expanded(
                              child: new Container(
                                child: new Text(
                                  device.exception_message,
                                  textAlign: TextAlign.center,
                                  style: new TextStyle(
                                    color: Colors.red,
                                  ),
                                ),
                                decoration: new BoxDecoration(
                                  border: Border(
                                    top: BorderSide(
                                      color: Colors.black38,
                                      width: 0.5,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                ],
              ),
              onPressed: () {
                showModalBottomSheet(
                  context: context,
                  builder: (ctx) {
                    return new Container(
                        child: new Column(
                      children: <Widget>[
                        new Expanded(
                          child: new Scrollbar(
                            child: new ListView(
                              children: <Widget>[
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备名称")),
                                      new Text(device.device_name),
                                      new CupertinoButton(
                                        padding: EdgeInsets.only(left: 5.0),
                                        child: new Icon(
                                          Icons.edit,
                                          color: Colors.green,
                                        ),
                                        onPressed: () {
                                          String newDeviceName = device.device_name;
                                          Navigator.of(context).pop();
                                          showDialog<Null>(
                                            context: context,
                                            builder: (context) {
                                              return new AlertDialog(
                                                title: new Text("修改设备名"),
                                                content: new TextField(
                                                  controller: new TextEditingController(text: device.device_name),
                                                  decoration: new InputDecoration(
                                                    hintText: '请输入新设备名',
                                                    labelText: "设备名",
                                                  ),
                                                  onChanged: (value) {
                                                    newDeviceName = value;
                                                  },
                                                ),
                                                actions: <Widget>[
                                                  new FlatButton(
                                                    onPressed: () async {
                                                      print(newDeviceName);
                                                      if (newDeviceName == "") {
                                                        toast("设备名名不能为空");
                                                        return;
                                                      }
                                                      var result = await setDeviceName(device.sessionid, device.userid, device.device_id, newDeviceName);
                                                      if (result) {
                                                        Navigator.of(context).pop();
                                                        toast("设备名修改成功");
                                                        device.device_name = newDeviceName;
                                                        device.update();
                                                        setState(() {});
                                                      }
                                                    },
                                                    child: new Text(
                                                      '修改',
                                                    ),
                                                  ),
                                                  new FlatButton(
                                                    onPressed: () async {
                                                      Navigator.of(context).pop();
                                                    },
                                                    child: new Text(
                                                      '取消',
                                                    ),
                                                  ),
                                                ],
                                              );
                                            },
                                          );
                                        },
                                        minSize: 22.0,
                                      ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("登录账号")),
                                      new Text(device.account),
                                      new CupertinoButton(
                                        padding: EdgeInsets.only(left: 5.0),
                                        onPressed: () {
                                          Navigator.pop(context);
                                          showDialog<Null>(
                                            context: context,
                                            builder: (context) {
                                              return new AlertDialog(
                                                title: new Text("解除绑定"),
                                                content: new Text("确定要将设备与此账号解除绑定吗？"),
                                                actions: <Widget>[
                                                  new FlatButton(
                                                    onPressed: () async {
                                                      var unBindResult = await unBindDevice(device.sessionid, device.userid, device.device_id);
                                                      if (unBindResult) {
                                                        refreshDevice(device);
                                                        Navigator.pop(context);
                                                      }
                                                    },
                                                    child: new Text(
                                                      '解除绑定',
                                                      style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
                                                    ),
                                                  ),
                                                  new FlatButton(
                                                    onPressed: () {
                                                      Navigator.pop(context);
                                                    },
                                                    child: new Text(
                                                      '取消',
                                                    ),
                                                  ),
                                                ],
                                              );
                                            },
                                          );
                                        },
                                        child: new ImageIcon(
                                          AssetImage("images/unlink.png"),
                                          color: Colors.red,
                                        ),
                                        minSize: 22.0,
                                      ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("磁盘1")),
                                      device.capacity_1 > 0 ? new Text(convertSize(device.used_1) + "/" + convertSize(device.capacity_1)) : new Text("未插入磁盘"),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("磁盘2")),
                                      device.capacity_2 > 0 ? new Text(convertSize(device.used_2) + "/" + convertSize(device.capacity_2)) : new Text("未插入磁盘"),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("绑定钱包")),
                                      new Text(device.addr != "" ? ("0x****" + device.addr.substring(device.addr.length - 6)) : "未绑定"),
                                      device.addr != ""
                                          ? new CupertinoButton(
                                              padding: EdgeInsets.only(left: 5.0),
                                              child: new Icon(
                                                Icons.info,
                                                color: Colors.green,
                                              ),
                                              onPressed: () {
                                                Navigator.of(context).pop();
                                                showDialog<Null>(
                                                  context: context,
                                                  builder: (context) {
                                                    return new AlertDialog(
                                                      title: new Text("钱包地址"),
                                                      content: new RepaintBoundary(
                                                        key: qrKey,
                                                        child: new Column(
                                                          mainAxisSize: MainAxisSize.min,
                                                          children: <Widget>[
                                                            new Text(
                                                              device.addr,
                                                              softWrap: true,
                                                            ),
                                                            new SizedBox(
                                                              height: 10.0,
                                                            ),
                                                            new CustomPaint(
                                                              size: new Size(200.0, 200.0),
                                                              painter: new QrPainter(data: device.addr, version: 4),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                      actions: <Widget>[
                                                        new FlatButton(
                                                          child: new Text(
                                                            "复制",
                                                          ),
                                                          padding: EdgeInsets.all(0.0),
                                                          onPressed: () {
                                                            Clipboard.setData(new ClipboardData(text: device.addr));

                                                            toast("已复制");
                                                            Navigator.of(context).pop();
                                                          },
                                                        ),
                                                        new FlatButton(
                                                          onPressed: () async {
                                                            Navigator.of(context).pop();
                                                            Navigator.of(context).push(
                                                              new CupertinoPageRoute(builder: (context) {
                                                                return new BlockPage(mainColor, addr: device.addr);
                                                              }),
                                                            );
                                                          },
                                                          child: new Text(
                                                            '区块查询',
                                                          ),
                                                        ),
                                                        new FlatButton(
                                                          onPressed: () async {
                                                            Navigator.of(context).pop();
                                                          },
                                                          child: new Text(
                                                            '关闭',
                                                          ),
                                                        ),
                                                      ],
                                                    );
                                                  },
                                                );
                                              },
                                              minSize: 22.0,
                                            )
                                          : new CupertinoButton(
                                              padding: EdgeInsets.only(left: 5.0),
                                              child: new Icon(
                                                Icons.link,
                                                color: Colors.green,
                                              ),
                                              onPressed: () async {
                                                Navigator.of(context).pop();
                                                var sendResult = await getSmsCode(device.account, sessionid: device.sessionid, userid: device.userid);
                                                if (sendResult['iRet'] == 0) {
                                                  toast("验证码发送成功");
                                                  showBindSmsCodeAlert(device);
                                                } else if (sendResult['iRet'] == -122) {
                                                  toast("请输入图片验证码");
                                                  var imgCode = await getImageCode(sendResult['sMsg']);
                                                  showBindImgCodeAlert(device, imgCode);
                                                } else {
                                                  toast(sendResult['sMsg']);
                                                }
                                              },
                                              minSize: 22.0,
                                            ),
                                      device.addr != ""
                                          ? new CupertinoButton(
                                              padding: EdgeInsets.only(left: 5.0),
                                              child: new ImageIcon(
                                                AssetImage("images/unlink.png"),
                                                color: Colors.red,
                                              ),
                                              onPressed: () async {
                                                Navigator.of(context).pop();
                                                var sendResult = await getSmsCode(device.account, sessionid: device.sessionid, userid: device.userid);
                                                if (sendResult['iRet'] == 0) {
                                                  toast("验证码发送成功");
                                                  showUnbindSmsCodeAlert(device);
                                                } else if (sendResult['iRet'] == -122) {
                                                  toast("请输入图片验证码");
                                                  var imgCode = await getImageCode(sendResult['sMsg']);
                                                  showUnbindImgCodeAlert(device, imgCode);
                                                } else {
                                                  toast(sendResult['sMsg']);
                                                }
                                              },
                                              minSize: 22.0,
                                            )
                                          : new Text(""),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备SN")),
                                      new Text(device.device_sn),
                                      new CupertinoButton(
                                        padding: EdgeInsets.only(left: 5.0),
                                        child: new Icon(
                                          Icons.content_copy,
                                          color: Colors.green,
                                        ),
                                        onPressed: () {
                                          Clipboard.setData(new ClipboardData(text: device.device_sn));
                                          toast("已复制");
                                        },
                                        minSize: 22.0,
                                      ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备ID")),
                                      new Text(device.device_id),
                                      new CupertinoButton(
                                        padding: EdgeInsets.only(left: 5.0),
                                        child: new ImageIcon(
                                          AssetImage("images/qrcode.png"),
                                          color: Colors.green,
                                        ),
                                        onPressed: () {
                                          Navigator.of(context).pop();
                                          showDialog<Null>(
                                            context: context,
                                            builder: (context) {
                                              return new AlertDialog(
                                                title: new Text(device.device_name + "设备码"),
                                                content: new RepaintBoundary(
                                                  key: qrKey,
                                                  child: new Column(
                                                    mainAxisSize: MainAxisSize.min,
                                                    children: <Widget>[
                                                      new SizedBox(
                                                        height: 10.0,
                                                      ),
                                                      new CustomPaint(
                                                        size: new Size(200.0, 200.0),
                                                        painter: new QrPainter(data: device.addr, version: 4),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                                actions: <Widget>[
                                                  new FlatButton(
                                                    child: new Text(
                                                      "复制ID",
                                                    ),
                                                    padding: EdgeInsets.all(0.0),
                                                    onPressed: () {
                                                      Clipboard.setData(new ClipboardData(text: device.device_id));
                                                      toast("已复制");
                                                    },
                                                  ),
                                                  new FlatButton(
                                                    onPressed: () async {
                                                      Navigator.of(context).pop();
                                                    },
                                                    child: new Text(
                                                      '关闭',
                                                    ),
                                                  ),
                                                ],
                                              );
                                            },
                                          );
                                        },
                                        minSize: 22.0,
                                      ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("MAC地址")),
                                      new Text(device.mac_address),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("内网IP")),
                                      new Text(device.lan_ip),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("固件版本")),
                                      new Text(device.system_version),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备型号")),
                                      new Text(device.hardware_model),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("绑定时间")),
                                      new Text(device.bind_time),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("激活天数")),
                                      new Text(device.bind_days),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        new Container(
                          color: Colors.white,
                          child: new Column(
                            children: <Widget>[
                              new Row(
                                children: <Widget>[
                                  new Expanded(
                                    child: new PopupMenuButton<int>(
                                      padding: const EdgeInsets.all(2.0),
                                      elevation: 2.0,
                                      child: new Column(
                                        children: <Widget>[
                                          new Icon(
                                            Icons.transform,
                                            size: 26.0,
                                          ),
                                          new Text("更换分组"),
                                        ],
                                      ),
                                      onSelected: (int value) async {
                                        var transResult = await updateDeviceGroup(device.id, device.group_id, value);
                                        print(transResult);
                                        if (transResult) {
                                          groups[findGroupIndex(device)].devices.remove(device);
                                          for (int i = 0; i < groups.length; i++) {
                                            if (groups[i].id == value) {
                                              groups[i].devices.add(device);
                                              break;
                                            }
                                          }
                                          Navigator.of(context).pop();
                                          toast("更换分组成功");
                                          setState(() {});
                                        }
                                      },
                                      itemBuilder: (BuildContext context) => groups.map((group) {
                                            return PopupMenuItem<int>(
                                              value: group.id,
                                              child: new Text(group.name),
                                            );
                                          }).toList(),
                                    ),
                                  ),
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () async {
                                        Navigator.pop(context);
                                        showDialog<Null>(
                                          context: context,
                                          builder: (context) {
                                            return new AlertDialog(
                                              title: new Text("弹出磁盘"),
                                              content: new Text("此操作将弹出全部磁盘，确定要弹出吗？"),
                                              actions: <Widget>[
                                                new FlatButton(
                                                  onPressed: () async {
                                                    var unMountResult = await unMountDisk(device.sessionid, device.userid, device.device_id);
                                                    if (unMountResult) {
                                                      refreshDevice(device);
                                                      Navigator.pop(context);
                                                    }
                                                  },
                                                  child: new Text(
                                                    '弹出磁盘',
                                                    style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
                                                  ),
                                                ),
                                                new FlatButton(
                                                  onPressed: () {
                                                    Navigator.pop(context);
                                                  },
                                                  child: new Text(
                                                    '取消',
                                                  ),
                                                ),
                                              ],
                                            );
                                          },
                                        );
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/export.png"),
                                            size: 30.0,
                                            color: Colors.red,
                                          ),
                                          new Text("弹出磁盘"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () {
                                        Navigator.pop(context);
                                        showDialog<Null>(
                                          context: context,
                                          builder: (context) {
                                            return new AlertDialog(
                                              title: new Text("重置设备"),
                                              content: new Text("确定要重置设备吗？"),
                                              actions: <Widget>[
                                                new FlatButton(
                                                  onPressed: () async {
                                                    var resetResult = await resetDevice(device.sessionid, device.userid, device.device_id);
                                                    if (resetResult) {
                                                      refreshDevice(device);
                                                      Navigator.pop(context);
                                                    }
                                                  },
                                                  child: new Text(
                                                    '重置设备',
                                                    style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
                                                  ),
                                                ),
                                                new FlatButton(
                                                  onPressed: () {
                                                    Navigator.pop(context);
                                                  },
                                                  child: new Text(
                                                    '取消',
                                                  ),
                                                ),
                                              ],
                                            );
                                          },
                                        );
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/reset.png"),
                                            size: 30.0,
                                            color: Colors.red,
                                          ),
                                          new Text("重置设备"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        deleteDevice(device);
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/delete.png"),
                                            size: 30.0,
                                            color: Colors.red,
                                          ),
                                          new Text("删除账号"),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              new Divider(
                                height: 1.0,
                              ),
                              new Row(
                                children: <Widget>[
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        Navigator.of(context).push(
                                          new CupertinoPageRoute(builder: (context) {
                                            return new IncomeRecordPage(device, mainColor);
                                          }),
                                        );
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/income.png"),
                                            size: 30.0,
                                          ),
                                          new Text("历史收入"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () async {
                                        Navigator.pop(context);
                                        drawDevice(device, true);
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/withdraw.png"),
                                            size: 30.0,
                                          ),
                                          new Text("申请提币"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        Navigator.of(context).push(
                                          new CupertinoPageRoute(builder: (context) {
                                            return new DrawRecordPage(device, mainColor);
                                          }),
                                        );
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/drawhistory.png"),
                                            size: 30.0,
                                          ),
                                          new Text("提币记录"),
                                        ],
                                      ),
                                    ),
                                  ),
                                  new Expanded(
                                    child: new FlatButton(
                                      padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                      onPressed: () {
                                        Navigator.of(context).pop();
                                        Navigator.of(context).push(
                                          new CupertinoPageRoute(builder: (context) {
                                            return new DownloadPage(device, mainColor);
                                          }),
                                        );
                                      },
                                      child: new Column(
                                        children: <Widget>[
                                          new ImageIcon(
                                            AssetImage("images/download.png"),
                                            size: 30.0,
                                          ),
                                          new Text("远程下载"),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ));
                  },
                );
              },
            ),
    );
  }

  Widget _pulldownBuilder(context, mode) {
    return new ClassicIndicator(
      mode: mode,
      idleText: "继续下拉刷新",
      completeText: "刷新完成",
      refreshingText: "刷新中…",
      releaseText: "松手开始刷新",
      refreshingIcon: const CupertinoActivityIndicator(),
      completeIcon: const Icon(Icons.done, size: 32.0, color: Colors.green),
    );
  }

  @override
  Widget build(BuildContext ctx) {
    return MaterialApp(
      home: new Scaffold(
        appBar: new CupertinoNavigationBar(
          backgroundColor: mainColor,
          middle: new Text(
            "玩客随行",
            style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
          ),
          border: new Border(bottom: BorderSide.none),
          leading: new PopupMenuButton<String>(
            padding: const EdgeInsets.all(2.0),
            elevation: 2.0,
            offset: Offset(0.0, 60.0),
            child: new Icon(
              Icons.sort_by_alpha,
              size: 22.0,
              color: Colors.white,
            ),
            onSelected: (String value) {
              switch (value) {
                case "income_desc":
                  groups.forEach((group) {
                    group.devices.sort((DeviceModel a, DeviceModel b) => b.yesterday_income.compareTo(a.yesterday_income));
                  });
                  this.sortRule = "income_desc";
                  setState(() {});
                  break;
                case "income_asc":
                  groups.forEach((group) {
                    group.devices.sort((DeviceModel a, DeviceModel b) => a.yesterday_income.compareTo(b.yesterday_income));
                  });
                  this.sortRule = "income_asc";
                  setState(() {});
                  break;
                case "name_desc":
                  groups.forEach((group) {
                    group.devices.sort((DeviceModel a, DeviceModel b) => b.device_name.compareTo(a.device_name));
                  });
                  this.sortRule = "name_desc";
                  setState(() {});
                  break;
                case "name_asc":
                  groups.forEach((group) {
                    group.devices.sort((DeviceModel a, DeviceModel b) => a.device_name.compareTo(b.device_name));
                  });
                  this.sortRule = "name_asc";
                  setState(() {});
                  break;
                default:
                  return;
              }
            },
            itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                  new CheckedPopupMenuItem<String>(
                    value: 'income_desc',
                    checked: this.sortRule == "income_desc",
                    child: new Text("产量由高至低"),
                  ),
                  new CheckedPopupMenuItem<String>(
                    value: 'income_asc',
                    checked: this.sortRule == "income_asc",
                    child: new Text("产量由低至高"),
                  ),
                  new CheckedPopupMenuItem<String>(
                    value: 'name_desc',
                    checked: this.sortRule == "name_desc",
                    child: new Text("设备名Z-a"),
                  ),
                  new CheckedPopupMenuItem<String>(
                    value: 'name_asc',
                    checked: this.sortRule == "name_asc",
                    child: new Text("设备名a-Z"),
                  ),
                ],
          ),
          trailing: new PopupMenuButton<String>(
            padding: EdgeInsets.zero,
            offset: Offset(0.0, 60.0),
            onSelected: (value) {
              switch (value) {
                case "add_account":
                  Navigator.of(context).push(
                    new CupertinoPageRoute(builder: (context) {
                      return new AddPage(groups, mainColor);
                    }),
                  ).then((value) async {
                    if (value == null) return;
                    var device = await findDeviceById(value);
                    if (device != null) {
                      for (var i = 0; i < groups.length; i++) {
                        if (groups[i].id == device['group_id']) {
                          groups[i].devices.add(new DeviceModel().fromMap(device));
                          refreshDevice(groups[i].devices.last);
                          deviceCount++;
                          break;
                        }
                      }
                      if (mounted) {
                        setState(() {});
                      }
                    } else {
                      toast("添加出错，请重试");
                    }
                  });
                  break;
                case "import_export":
                  Navigator.of(context).push(
                    new CupertinoPageRoute(builder: (context) {
                      return new ImportPage(mainColor);
                    }),
                  ).then((value) {
                    if (value) {
                      initGroups();
                    }
                  });
                  break;
                case "add_group":
                  showDialog<Null>(
                    context: ctx,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("添加分组"),
                        content: new Container(
                            height: 75.0,
                            child: new Column(
                              children: <Widget>[
                                new TextField(
                                  decoration: new InputDecoration(
                                    hintText: '请输入分组名',
                                    labelText: "分组名",
                                  ),
                                  onChanged: (value) {
                                    addGroupName = value;
                                  },
                                ),
                              ],
                            )),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                          new FlatButton(
                            onPressed: () async {
                              if (addGroupName == "") {
                                toast("请输入分组名");
                                return null;
                              }
                              var addRes = await addGroup(addGroupName);
                              groups.add(
                                new GroupModel(id: addRes, name: addGroupName, devices: []),
                              );
                              addGroupName = "";
                              if (addRes != null) {
                                Navigator.of(context).pop();
                                toast("添加分组成功");
                              }
                              if (mounted) {
                                setState(() {});
                              }
                            },
                            child: new Text(
                              '添加',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      );
                    },
                  );
                  break;
              }
            },
            child: new Icon(
              Icons.add,
              size: 22.0,
              color: Colors.white,
            ),
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                  const PopupMenuItem<String>(
                    value: 'add_account',
                    child: const ListTile(
                      leading: const Icon(Icons.person_add),
                      title: const Text('添加设备'),
                    ),
                  ),
                  const PopupMenuItem<String>(
                    value: 'import_export',
                    child: const ListTile(
                      leading: const Icon(Icons.import_export),
                      title: const Text('导入导出'),
                    ),
                  ),
                  const PopupMenuDivider(),
                  const PopupMenuItem<String>(
                    value: 'add_group',
                    child: const ListTile(
                      leading: const Icon(Icons.group_add),
                      title: const Text('添加分组'),
                    ),
                  )
                ],
          ),
          actionsForegroundColor: Colors.white,
        ),
        body: new Container(
          color: Colors.white,
          child: new Column(
            children: <Widget>[
              indexHeader(),
              new Expanded(
                child: new Scrollbar(
                  child: new SmartRefresher(
                    enablePullDown: true,
                    onRefresh: refreshAll,
                    headerBuilder: _pulldownBuilder,
                    controller: _refreshController,
                    child: new ListView.builder(
                      itemCount: groups.length,
                      itemBuilder: (context, i) => _buildGroup(groups[i]),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}
